package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return memberService.findPage(queryPageBean);

    }


    //新增会员
    @RequestMapping("/add")
    public Result add (@RequestBody Member member){
        try {
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.ADD_MEMBER_FAIL);
        }
    }


    //根据id查询会员信息
    @RequestMapping("/findById")
    public Result findById(Integer id){

        try {
            Member member = memberService.findById(id);
            return new Result(true,"获取会员信息成功",member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"获取会员信息失败");
        }

    }


    //编辑会员信息
    @RequestMapping("/edit")
    public Result edit (@RequestBody Member member){
        try {
            memberService.edit(member);
            return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.EDIT_MEMBER_FAIL);
        }
    }


    //删除会员信息
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            memberService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL+"!...该会员还有预约的套餐没到诊！");
        }
    }


    //批量导出到Excel文件
   @RequestMapping("/exportExcel")
    public Result exportExcel(Integer[] ids, HttpServletRequest request, HttpServletResponse response){
        try {
            List<Member> members =  memberService.findByMemberId(ids);

            String filePath = request.getSession().getServletContext().
                    getRealPath("/template") + File.separator + "member.xlsx";

            //基于POI在内存中创建一个Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));

            XSSFSheet sheet = excel.getSheetAt(0);



            int rows = 1;


            for (Member member : members) {
                List<String> checkGroupss = new ArrayList<>();
                List<String> checkItemss = new ArrayList<>();
                //名字
                String name = member.getName();
                XSSFRow row = sheet.createRow(rows++);
                System.out.println("==========="+row);
                row.createCell(0).setCellValue(name);

                //性别
                String sex = member.getSex();
                row.createCell(1).setCellValue(sex);


                //电话号码
                String phoneNumber = member.getPhoneNumber();
                row.createCell(2).setCellValue(phoneNumber);



                //机构地址
                String address = member.getAddress();
                row.createCell(3).setCellValue(address);


                Setmeal setMeal = member.getSetMeals();

                    //套餐名称
                String setMealName = null;
                String group = null;
                String item = null;
                try {
                    setMealName = setMeal.getName();
                    row.createCell(4).setCellValue(setMealName);



                    List<CheckGroup> checkGroups = setMeal.getCheckGroups();
                    for (CheckGroup checkGroup : checkGroups) {
                        String groupName = checkGroup.getName();
                        checkGroupss.add(groupName);

                        List<CheckItem> checkItems = checkGroup.getCheckItems();
                        for (CheckItem checkItem : checkItems) {
                            String itemName = checkItem.getName();
                            checkItemss.add(itemName);
                        }
                    }

                    group = checkGroupss.toString();
                    item = checkItemss.toString();

                    row.createCell(5).setCellValue(group);
                    row.createCell(6).setCellValue(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=member.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,"导出失败");
        }

    }





}
